import wave
import numpy as np
import difflib

def load_pinyin_dict(filename):
    pinyin_list=list()
    pinyin_dict=dict()
    with open(filename, 'r', encoding='utf8') as f:
        lines=f.read().split('\n')
    for line in lines:
        if len(line) == 0:
            continue
        tokens=line.split('\t')
        pinyin_list.append(tokens[0])
        pinyin_dict[tokens[0]]=len(pinyin_list)-1
    return pinyin_list,pinyin_dict

def read_wav_data(filename):
    '''
    读取一个wav文件，返回声音信号的时域谱矩阵、采样率、通道数和位深
    '''
    wav=wave.open(filename,'rb')
    num_frame=wav.getnframes()
    num_channel=wav.getnchannels()
    framerate=wav.getframerate()
    num_sample_width=wav.getsampwidth()
    str_data=wav.readframes(num_frame)
    wav.close()
    if num_sample_width==2:
        dtype=np.short
    else:
        dtype=np.short
    wave_data=np.frombuffer(str_data,dtype=dtype)
    wave_data.shape=-1,num_channel
    wave_data=wave_data.T
    return wave_data,framerate,num_channel,num_sample_width

def ctc_decode_delete_tail_blank(ctc_decode_list):
    '''处理CTC解码后序列末尾余留的空白元素，删除掉'''
    p=0
    while p<len(ctc_decode_list) and ctc_decode_list[p]!=-1:
        p+=1
    return ctc_decode_list[0:p]

def get_edit_distance(str1:list, str2:list) -> int:
    """
    计算两个串的编辑距离，支持str和list类型
    str1和str2是列表，列表元素是要比的字符串，计算对应位置字符串的编辑距离
    """
    leven_cost = 0
    print(f'--str1-str2-{str1}-{str2}')
    for s1,s2 in zip(str1,str2):
        sequence_match = difflib.SequenceMatcher(None, s1, s2)
        for tag, index_1, index_2, index_j1, index_j2 in sequence_match.get_opcodes():
            if tag == 'replace':
                leven_cost += max(index_2-index_1, index_j2-index_j1)
            elif tag == 'insert':
                leven_cost += (index_j2-index_j1)
            elif tag == 'delete':
                leven_cost += (index_2-index_1)
            # print(tag,index_1,index_2,index_j1,index_j2)
    # m,n=len(str1),len(str2)
    # dp=[]
    # for i in range(m+1):
    #     dp.append([0 for j in range(n+1)])
    # for i in range(1,m+1):
    #     dp[i][0]=i
    # for j in range(1,n+1):
    #     dp[0][j]=j
    # for i in range(1,m+1):
    #     for j in range(1,n+1):
    #         if str1[i-1]==str2[j-1]:
    #             dp[i][j]=min(dp[i-1][j]+1,dp[i][j-1]+1,dp[i-1][j-1])
    #         else:
    #             dp[i][j]=min(dp[i-1][j]+1,dp[i][j-1]+1,dp[i-1][j-1]+1)
    # return dp[m][n]

    return leven_cost

def get_language_model(model_language_filename):
    """
    读取语言模型的文件
    返回读取后的模型
    """
    txt_obj = open(model_language_filename, 'r', encoding='UTF-8')  # 打开文件并读入
    txt_text = txt_obj.read()
    txt_obj.close()
    txt_lines = txt_text.split('\n')  # 文本分割

    dic_model = {}  # 初始化符号字典
    for i in txt_lines:
        if i != '':
            txt_l = i.split('\t')
            if len(txt_l) == 1:
                continue
            dic_model[txt_l[0]] = float(txt_l[1])

    return dic_model

if __name__=='__main__':
    res=get_edit_distance('abc','ABC')
    print(res)